<template>
  <el-card class="card">
    <h2>个人中心</h2>
    <el-descriptions title="个人信息" :column="3" border>
      <el-descriptions-item
        label="学号"
        label-align="center"
        align="center"
        label-class-name="my-label"
        class-name="my-content"
        width="150px"
        >{{ this.user.identityId }}</el-descriptions-item
      >
      <el-descriptions-item
        label="姓名"
        label-align="center"
        align="center"
        width="150px"
      >
        {{ this.user.realName }}</el-descriptions-item
      >
      <el-descriptions-item
        label="性别"
        label-align="center"
        align="center"
        width="150px"
        >{{ this.user.gender }}
      </el-descriptions-item>
      <el-descriptions-item label="用户名" label-align="center" align="center">
        {{ this.user.username }}
      </el-descriptions-item>
      <el-descriptions-item label="积分" label-align="center" align="center">
        {{ this.user.integral }}
      </el-descriptions-item>
      <el-descriptions-item label="出生日期" label-align="center" align="center"
        >{{ getTime }}
      </el-descriptions-item>
      <el-descriptions-item label="账户" label-align="center" align="center">
        {{ this.user.account }}
      </el-descriptions-item>
      <el-descriptions-item label="手机号" label-align="center" align="center">
        {{ this.user.tel }}
      </el-descriptions-item>
      <el-descriptions-item label="邮箱" label-align="center" align="center">
        {{ this.user.email }}
      </el-descriptions-item>
      <el-descriptions-item label="学校" label-align="center" align="center">
        <el-tag>{{ this.user.school }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="学院" label-align="center" align="center">
        <el-tag>{{ this.user.academy }}</el-tag>
      </el-descriptions-item>
    </el-descriptions>
    <el-row class="mb">
      <el-button type="primary" round @click="clickHandler1"
        >编辑信息</el-button
      >
      <el-button type="primary" round @click="up">上传头像</el-button>
      <el-button type="primary" round @click="clickHandler2"
        >修改密码</el-button
      >
      <el-button type="primary" round @click="clickHandler4"
        >更改绑定</el-button
      >
      <el-button type="primary" round @click="clickHandler3"
        >退出登录</el-button
      >
    </el-row>
  </el-card>
  <div>
    <el-dialog v-model="dialogFormVisible1" title="编辑信息">
      <el-form :model="user" ref="form1" :rules="rules">
        <el-row>
          <el-form-item
            label="学号"
            :label-width="formLabelWidth"
            prop="identityId"
          >
            <el-input
              v-model="user.identityId"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
          <el-form-item
            label="姓名"
            :label-width="formLabelWidth"
            prop="realName"
          >
            <el-input
              v-model="user.realName"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="昵称"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              v-model="user.username"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-select v-model="user.gender" placeholder="男">
              <el-option label="男" value="男" />
              <el-option label="女" value="女" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="手机号" :label-width="formLabelWidth" prop="tel">
            <el-input
              v-model="user.tel"
              autocomplete="off"
              style="width: 219px"
              
            />
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input
              v-model="user.email"
              autocomplete="off"
              style="width: 219px"
           
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="学校"
            :label-width="formLabelWidth"
            prop="school"
          >
            <el-input
              v-model="user.school"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
          <el-form-item
            label="学院"
            :label-width="formLabelWidth"
            prop="academy"
          >
            <el-input
              v-model="user.academy"
              autocomplete="off"
              style="width: 219px"
            />
          </el-form-item>
        </el-row>

        <el-form-item label="出生日期" :label-width="formLabelWidth">
          <el-date-picker
            v-model="user.birth"
            type="date"
            placeholder="Pick a day"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancle()">取消</el-button>
          <el-button type="primary" @click="edit()">修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-dialog
      v-model="dialogFormVisible2"
      title="修改密码"
      width="30%"
      align-center
    >
      <el-form :model="form2" :rules="rules" ref="form2">
        <el-form-item
          label="新密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            type="password"
            v-model="form2.password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="确认新密码"
          :label-width="formLabelWidth"
          prop="repassword"
        >
          <el-input
            type="password"
            v-model="form2.repassword"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelChange()">取消</el-button>
          <el-button type="primary" @click="changePassword()">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible3" title="是否退出登录">
      <el-button @click="dialogFormVisible3 = false">取消</el-button>
      <el-button type="primary" @click="signOut()">确定</el-button>
    </el-dialog>
    <el-dialog
      v-model="dialogTableVisible"
      title="人物头像"
      center
      align-center
    >
      <el-upload
        ref="uploadDemo"
        class="upload-demo"
        drag
        :before-upload="beforUpload"
        :headers="headerObj"
        :action="targetUrl"
        :file-list="fileList"
        list-type="picture"
        :on-success="uploadSuccess"
        :on-error="uploadFail"
        :limit="1"
        :on-exceed="exceed"
        :auto-upload="false"
        accept=".jpg,.png,.JPG,.PNG"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          Drop file here or <em>click to upload</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            jpg/png files with a size less than 5M
            <el-button
              size="small"
              style="margin-left: 50px"
              @click="dialogTableVisible = false"
              >取 消</el-button
            >
            <el-button size="small" type="primary" @click="upload1"
              >确 定</el-button
            >
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { mapGetters, mapMutations } from "vuex";
import { queryById, update, changePassword } from "../../api/user.js";
import { toRaw } from "@vue/reactivity";
import { ElMessage } from "element-plus";
import mitt from "@/plugins/mitt";
export default {
  // 数据源
  data() {
    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        // alert('请再次输入密码')
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form2.password) {
        // alert('两次输入密码不一致!')
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      rules: {
        identityId: [{ required: true, message: "学号是必填项" }],
        username: [{ required: true, message: "昵称是必填项" }],
        realName: [{ required: true, message: "姓名是必填项" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            pattern:
              /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,30}$/,
            message:
              "密码为数字、小写字母、大写字母、特殊符号，至少包含三种，长度为8 - 30位",
          },
        ],
        repassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        tel: [
          { required: true, message: "请输入电话号", trigger: "blur" },
          {
            pattern:
              /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/,
            message: "请输入正确的手机号",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱号", trigger: "blur" },
          {
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: "请输入正确的邮箱",
          },
        ],
        school: [{ required: true, message: "学校是必填项" }],
        academy: [{ required: true, message: "学院是必填项" }],
      },
      form2: {
        password: "",
        repassword: "",
      },
      formLabelWidth: "140px",
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      dialogTableVisible: false,
      user: {
        identityId: "",
        id: "",
        tel: "",
        username: "",
        realName: "",
        password: "",
        gender: "",
        birth: "",
        role: "",
        picture: "",
        account: "",
        integral: "",
        email: "",
        lastTime: "",
        createTime: "",
        school: "",
        academy: "",
      },
      url: "http://localhost:8088/api/user/uploadUserImage",
      targetUrl: "",
      fileList: [],
    };
  },
  //生命周期函数---
  mounted() {
    this.getData();
  },
  //基本方法
  methods: {
    ...mapMutations({
      changeOffOnline: "changeOffOnline",
    }),
    edit() {
      this.$refs.form1.validate((val) => {
        if (val) {
          let temp = toRaw(this.user);
          update(temp).then((res) => {
            if (res.code == 200) {
              this.getData();
              ElMessage({
                type: "success",
                message: "更新成功",
              });
            } else {
              ElMessage({
                type: "error",
                message: "信息更新失败",
              });
            }
          });
          this.dialogFormVisible1 = false;
        }
      });
    },
    cancle() {
      this.dialogFormVisible1 = false;
      this.getData();
    },
    changePassword() {
      if (this.form2.password == this.form2.repassword) {
        this.$refs.form2.validate((val) => {
          if (val) {
            changePassword(this.user.id, this.form2.password).then((res) => {
              if (res.code == 200) {
                this.dialogFormVisible2 = false;
                ElMessage({
                  type: "success",
                  message: "修改成功，请重新登录",
                });
                this.signOut();
              } else {
                ElMessage({
                  type: "error",
                  message: "修改失败",
                });
              }
            });
          }
        });
      }
    },
    cancelChange() {
      this.dialogFormVisible2 = false;
      this.$refs.form2.resetFields();
    },
    signOut() {
      this.changeOffOnline();
      window.sessionStorage.removeItem("token");
      window.sessionStorage.removeItem("store");
      this.$router.push({
        path: "/home",
      });
    },
    clickHandler1(evt) {
      var that = this;
      that.dialogFormVisible1 = true;
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
    },
    clickHandler2(evt) {
      var that = this;
      that.dialogFormVisible2 = true;
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
    },
    clickHandler3(evt) {
      var that = this;
      that.dialogFormVisible3 = true;
      let target = evt.target;
      if (target.nodeName == "SPAN") {
        target = evt.target.parentNode;
      }
      target.blur();
    },
    clickHandler4(evt) {
      alert("更改绑定信息等待完善");
    },
    getData() {
      queryById(this.getId).then((res) => {
        if (res.code == 200) {
          this.user.id = res.data.id;
          this.user.identityId = res.data.identityId;
          this.user.tel = res.data.tel;
          this.user.username = res.data.username;
          this.user.realName = res.data.realName;
          this.user.password = res.data.password;
          this.user.gender = res.data.gender;
          this.user.birth = res.data.birth;
          this.user.role = res.data.role;
          this.user.picture = res.data.picture;
          this.user.account = res.data.account;
          this.user.integral = res.data.integral;
          this.user.email = res.data.email;
          this.user.lastTime = res.data.lastTime;
          this.user.createTime = res.data.createTime;
          this.user.school = res.data.school;
          this.user.academy = res.data.academy;
        }
      });
    },
    //修改用户头像
    up() {
      this.dialogTableVisible = true;
    },
    //图片文件上传相关操作
    exceed() {
      ElMessage({
        type: "warning",
        message: "一次只能上传一个文件",
      });
    },
    uploadSuccess(response) {
      this.fileList = [];
      this.dialogTableVisible = false;
      //根据返回值做出对应反馈
      if (response.code == 200) {
        ElMessage({
          type: "success",
          message: "上传成功",
        });
        this.test(response.data);
      } else {
        ElMessage({
          type: "error",
          message: "上传失败",
        });
      }
    },
    uploadFail() {
      ElMessage({
        type: "error",
        message: "上传失败",
      });
      this.fileList = [];
    },
    beforUpload() {
      this.targetUrl = this.url + `?id=${this.user.id}`;
    },
    // 对选中文件进行上传
    upload1() {
      //手动提交上传
      this.$refs.uploadDemo.submit();
    },
    test(url) {
      mitt.emit("changeAvatar", url);
    },
  },
  //计算类型方法和其他方法的区别：有缓存。以内存换时间，适用于频繁使用的计算
  computed: {
    ...mapGetters(["getId"]),
    getTime() {
      return moment(this.user.birth).format("YYYY-MM-DD");
    },
  },
};
</script>

<style   scoped>
.card {
  margin-top: 30px;
  width: 80%;
  border-radius: 10px;
  height: 408px;
}

.my-label {
  background: var(--el-color-success-light-9);
}

.my-content {
  background: var(--el-color-danger-light-9);
}

.mb {
  display: flex;
  justify-content: center;
  margin-top: 50px;
}
</style>